// 首页reducer

import { Channel, Articles } from '@/types/data'
import { HomeAction } from '@/types/store'

// 首页数据模块类型
type HomeState = {
  channels: Channel[]
  restChannel: Channel[]
  channelActiveKey: number
  channelArticles: {
    [key in number]: Articles
  }
}

const initialState: HomeState = {
  channels: [],
  restChannel: [],
  channelActiveKey: 0,
  channelArticles: {}
}

export const home = (state = initialState, action: HomeAction): HomeState => {
  // 处理频道数据
  if (action.type === '/home/getChannels') {
    return {
      ...state,
      channels: action.payload
    }
  }

  // 处理推荐频道（剩余频道数据）
  if (action.type === '/home/getRestChannel') {
    return {
      ...state,
      restChannel: action.payload
    }
  }
  // 修改频道选中状态数据
  if (action.type === 'home/toggleChannel') {
    return {
      ...state,
      channelActiveKey: action.payload
    }
  }
  // 删除频道
  if (action.type === 'home/delMyChannel') {
    return {
      ...state,
      // 用户频道删掉
      channels: state.channels.filter(item => item.id !== action.payload.id),
      // 剩余频道添加进来
      restChannel: [...state.restChannel, action.payload].sort((item1, item2) => item1.id - item2.id)
    }
  }
  if (action.type === 'home/addChannel') {
    return {
      ...state,
      // 添加到用户频道
      channels: [...state.channels, action.payload].sort((item1, item2) => item1.id - item2.id), // TODO 排序
      restChannel: state.restChannel.filter(item => item.id !== action.payload.id)
    }
  }
  // 合并处理频道列表数据
  if (action.type === 'home/getArticleList') {
    // 新来的数据
    const channelId = action.payload.channelId
    const newArticles = action.payload.articles

    // 当前state中的文章列表
    const currentArticles = state.channelArticles[channelId] || {
      pre_timestamp: Date.now(),
      results: []
    }

    return {
      ...state,
      channelArticles: {
        // 原来的所有频道文章展开，复制一份
        ...state.channelArticles,
        // 在原来的基础上更新，用户请求的频道文章数据
        [channelId]: {
          pre_timestamp: newArticles.pre_timestamp,
          results: [...currentArticles.results, ...newArticles.results]
        }
      }
    }
  }

  return state
}
